package com.cskaoyan.user.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.*;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.ILoginService;
import com.cskaoyan.user.service.IUserRegisterService;
import com.cskaoyan.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cskaoyan.user.dal.entitys.Token;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping( "/user" )
public class CaptchaController {

    @Autowired
    IKaptchaService kaptchaService;

    //yepq
    @Autowired
    IUserRegisterService iUserRegisterService;

    //yepq
    @Autowired
    IKaptchaService iKaptchaService;

    //yepq
    @Autowired
    ILoginService iLoginService;

    //yepq
    @Autowired
    UserService userService;


    /**
     * 获取验证码
     */
    @GetMapping( "/kaptcha" )
    public ResponseData getKaptchaCode(HttpServletResponse response) {
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest ( );
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.getKaptchaCode ( kaptchaCodeRequest );
        if (kaptchaCodeResponse.getCode ( ).equals ( UserRetCode.SUCCESS.getCode ( ) )) {
            Cookie cookie = CookieUtil.genCookie ( "kaptcha_uuid", kaptchaCodeResponse.getUuid ( ), "/", 60 );
            cookie.setHttpOnly ( true );
            response.addCookie ( cookie );
            return new ResponseUtil<> ( ).setData ( kaptchaCodeResponse.getImageCode ( ) );
        }
        return new ResponseUtil<> ( ).setErrorMsg ( kaptchaCodeResponse.getCode ( ) );
    }

    @PostMapping( "/kaptcha" )
    public ResponseData validKaptchaCode(@RequestBody String code, HttpServletRequest httpServletRequest) {
        KaptchaCodeRequest request = new KaptchaCodeRequest ( );
        String uuid = CookieUtil.getCookieValue ( httpServletRequest, "kaptcha_uuid" );
        request.setUuid ( uuid );
        // 用户输入的验证码
        request.setCode ( code );
        KaptchaCodeResponse response = kaptchaService.validateKaptchaCode ( request );
        if (response.getCode ( ).equals ( UserRetCode.SUCCESS.getCode ( ) )) {
            return new ResponseUtil<> ( ).setData ( null );
        }
        return new ResponseUtil<> ( ).setErrorMsg ( response.getCode ( ) );
    }

    /**
     * TODO: 注册的方法
     * author: yepq2025@outlook.com
     * time: 2022-12-02 23:20:59
     */
    @PostMapping( "/register" )
    public ResponseData register(@RequestBody UserRegisterRequest userRegisterRequest, HttpServletRequest httpServletRequest) {
        //验证验证码是否正确

        KaptchaCodeRequest request = new KaptchaCodeRequest ( );
//        KaptchaCodeResponse kaptchaCodeResponse;
        String uuid = CookieUtil.getCookieValue ( httpServletRequest, "kaptcha_uuid" );
        request.setUuid ( uuid );
        request.setCode ( userRegisterRequest.getCaptcha ( ) );
        KaptchaCodeResponse kaptchaCodeResponse1 = iKaptchaService.validateKaptchaCode ( request );
        //验证码错误
        if (!kaptchaCodeResponse1.getCode ( ).equals ( UserRetCode.SUCCESS.getCode ( ) )) {
            return new ResponseUtil<> ( ).setErrorMsg ( kaptchaCodeResponse1.getMsg ( ) );
        }
        //验证码正确
        UserRegisterResponse userRegisterResponse = iUserRegisterService.register ( userRegisterRequest );
        if (UserRetCode.SUCCESS.getCode ( ).equals ( userRegisterResponse.getCode ( ) )) {
            return new ResponseUtil ( ).setData ( userRegisterResponse );
        }
        return new ResponseUtil ( ).setErrorMsg ( userRegisterResponse.getMsg ( ) );

    }

    /**
     * TODO: 验证用户登录
     * author: yepq2025@outlook.com
     * time: 2022-12-04 16:05:53
    */
    @GetMapping("/login")
    public ResponseData verifyLogin(HttpServletRequest request) {
        // 验证是否带有user_info请求头， 由于user_info请求头是通过Cookie构造的，所以通过user_info判空来进行登录状态校验
        String userInfo = null;
        userInfo = request.getHeader ( "user_info" );
        if (userInfo == null) {
            return new ResponseUtil<> ().setErrorMsg ( UserRetCode.TOKEN_VALID_FAILED.getMessage () );
        }
        // 获取Token
        String token = null;
        token = CookieUtil.getCookieValue ( request, "access_token" );
        // 有Token进行校验解析
        Map<String, Object> verifyResult = iLoginService.verifyLogin(token);
        return new ResponseUtil<> ().setData ( verifyResult );
    }

    /**
     * TODO: 验证用户登录的方法
     * author: yepq2025@outlook.com
     * time: 2022-12-03 09:30:36
     * v001
     */
   /* @GetMapping( "/login" )
    public ResponseData login(HttpServletRequest request) {
        String userinfo = (String) request.getHeader ( "user info" );
        JSONObject object = JSON.parseObject ( userinfo );
        long uid = Long.parseLong ( object.get ( "uid" ).toString ( ) );
        AddressListRequest addressListRequest = new AddressListRequest ( );
        addressListRequest.setUserId ( uid );
        UserCheckResponse userCheckResponse = iLoginService.check ( addressListRequest );
        if (UserRetCode.SUCCESS.getCode ( ).equals ( userCheckResponse.getCode ( ) )) {
            return new ResponseUtil ( ).setData ( userCheckResponse );
        }
        return new ResponseUtil ( ).setErrorMsg ( userCheckResponse.getMsg ( ) );
    }*/

    /**
     * TODO: 登录的方法
     * author: yepq2025@outlook.com
     * time: 2022-12-03 09:40:03
     */
    @PostMapping( "/login" )
    public ResponseData login(@RequestBody UserRegisterRequest userLoginRequest, HttpServletResponse servletResponse, HttpServletRequest servletRequest) {
        // 首先验证验证码是否正确
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest ( );
        KaptchaCodeResponse kaptchaCodeResponse;
        String uuid = CookieUtil.getCookieValue ( servletRequest, "kaptcha_uuid" );
        kaptchaCodeRequest.setUuid ( uuid );
        kaptchaCodeRequest.setCode ( userLoginRequest.getCaptcha ( ) );
        KaptchaCodeResponse kaptchaCodeResponse1 = iKaptchaService.validateKaptchaCode ( kaptchaCodeRequest );

        // 验证码错误
        if (!kaptchaCodeResponse1.getCode ( ).equals ( UserRetCode.SUCCESS.getCode ( ) )) {
            return new ResponseUtil<> ( ).setErrorMsg ( kaptchaCodeResponse1.getMsg ( ) );
        }
        // 验证码成功
        UserLoginResponse response = iLoginService.login ( userLoginRequest );
        // 如果用户没有激活成功
        if (UserRetCode.USER_ISVERFIED_ERROR.getCode ( ).equals ( response.getCode ( ) )) {
            return new ResponseUtil<> ( ).setErrorMsg ( response.getMsg ( ) );
        }
        if (UserRetCode.SUCCESS.getCode ( ).equals ( response.getCode ( ) )) {
            // 如果登录成功，将返回数据，并且将token放入到请求头上
            // 首先产生一个含有username和id信息token
            Long uid = response.getId ( );
            String username = response.getUsername ( );
            Token token = new Token ( );
            token.setUid ( uid );
            token.setUsername ( username );
            String jsonString = JSON.toJSONString ( token );
            String jwtToken = JwtTokenUtils.builder ( ).msg ( jsonString ).build ( ).creatJwtToken ( );
            // 把令牌放入到cookie中
            Cookie cookie = new Cookie ( "access_token", jwtToken );
            cookie.setPath ( "/" );
            cookie.setMaxAge ( 3 * 60 * 60 );
            servletResponse.addCookie ( cookie );
            // 把令牌放入到请求头中
            servletResponse.setHeader ( "user_info", jwtToken );
            return new ResponseUtil ( ).setData ( response );
        }
        return new ResponseUtil ( ).setErrorMsg ( response.getMsg ( ) );
    }

    /**
     * TODO: 用户退出接口
     * author: yepq2025@outlook.com
     * time: 2022-12-03 10:35:48
     *
     * @return： {"success":true,"message":"success","code":200,"result":null,"timestamp":1587710244802}
     */
    @GetMapping( "/loginOut" )
    public ResponseData userLoginOut(HttpServletRequest request, HttpServletResponse response) {
        String access_token = CookieUtil.getCookieValue ( request, "access_token" );
        Cookie cookie = new Cookie ( "access_token", null );
        cookie.setMaxAge ( 0 );
        cookie.setPath ( "/" );
        response.addCookie ( cookie );

        return new ResponseUtil ( ).setData ( null );
    }

    /**
     * TODO: 用户注册激活
     * author: yepq2025@outlook.com
     * time: 2022-12-03 10:39:16
     *
     * @return {"success":true,"message":"success","code":200,"result":null,"timestamp":1587710244802}
     */
    @GetMapping( "/verify" )
    public ResponseData verify(String username, String uuid) {
        // 封装请求对象
        UserVerifyRequest verifyRequest = new UserVerifyRequest ( );
        verifyRequest.setUserName ( username );
        verifyRequest.setUuid ( uuid );

        // 执行业务逻辑
        // 并返回封装对象
        UserVerifyResponse response = userService.verifyUser ( verifyRequest );

        //返回对应的状态
        if (UserRetCode.SUCCESS.getCode ( ).equals ( response.getCode ( ) )) {
            // 执行成功
            return new ResponseUtil<> ( ).setData ( null );
        }
        // 执行失败
        return new ResponseUtil<> ( ).setErrorMsg ( response.getMsg ( ) );
    }
}
